import store from '@/store'
import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const wirteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        const routers = await store.dispatch('permission/filterRouters', menus)
        // 把有访问权限的路由添加到路由中  router.addRoutes() 路由自带的添加方法
        router.addRoutes([...routers, { path: '*', redirect: '/404', hidden: true }])
        // 相当于跳到对应的地址  相当于多做一次跳转
        next(to.path)
      }
      next()
    }
  } else {
    if (wirteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
